package src.main.kotlin.day91

/**
 * 4.泛型约束
 *
 */

fun main() {

    val box1:MagicBox4<boy4> = MagicBox4(boy4("jack", 20))

    //添加了约束
//    val box2:MagicBox4<Dog4> = MagicBox4(Dog4(30))

    box1.available = true
    box1.fetch()?.run {
        println("you find a ${this.name}")
    }

    val man = box1.fetch {
        Man4("jack", it.age.plus(15))

    }

    println(man)
}

//这里对泛型 T 进行约束成Human类型
class MagicBox4<T : Human>(item:T){
    var available = false
    private var subject:T = item
    fun fetch(): T?{
        return subject.takeIf { available  }
    }

    //TODO: 业务： 把元素进行修改
    //TODO: 容器中放了boy3，取出来的时候，修改成了其他
    fun <R>fetch(subjectModFunction:(T)->R):R?{
        return subjectModFunction(subject).takeIf { available }
    }
}

open class Human(val age:Int)
class boy4(val name: String, age:Int):Human(age)
class Man4(val name: String, age:Int):Human(age)


class Dog4(val weight:Int)

